package org.bunny.vehicle.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang.StringUtils;
import org.bunny.vehicle.entity.User;
import org.bunny.vehicle.util.Const;

public class PageProcessingServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public PageProcessingServlet() {
		super();
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		process(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		process(request, response);
	}

	private void process(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String requestUri = StringUtils
				.substringBeforeLast(
						StringUtils.substringAfter(request.getRequestURI(),
								request.getContextPath() + "/"), ".html");
		HttpSession session = request.getSession(false);

		if (null != session && null != session.getAttribute(Const.SESSION_USER)) {
			User user = (User) session.getAttribute(Const.SESSION_USER);
			request.setAttribute("user", user);
		}

		request.getRequestDispatcher(requestUri + ".jsp").forward(request, response);
	}

}
